<template>
    <div class="BoxBg">
        <div class="bodyBox">
            <div class="topEchartsBox">
                <div class="topEchartsLeft topSmallBox">
                    <div class="topLeft">
                        <span class="title">内容发布量</span>
                        <span class="number">{{ topLData.total || 0 }}</span>
                        <span class="comparison">较昨天&emsp;
                            <span class="comparisonGreen" v-if="topLData.increase >= 0">{{ topLData.increase
                                }}</span>
                            <span class="comparisonRed" v-else>{{ topLData.increase
                                }}</span>
                        </span>
                    </div>
                    <div class="topRight">
                        <div class="chartBox" ref="topL"></div>
                    </div>
                </div>
                <div class="topEchartsInt topSmallBox">
                    <div class="topLeft">
                        <span class="title">评论总量</span>
                        <span class="number">{{ topIData.total || 0 }}</span>
                        <span class="comparison">较昨天&emsp;
                            <span class="comparisonGreen" v-if="topLData.increase >= 0">{{ topLData.increase
                                }}</span>
                            <span class="comparisonRed" v-else>{{ topLData.increase
                                }}</span>
                        </span>
                    </div>
                    <div class="topRight">
                        <div class="chartBox" ref="topI"></div>
                    </div>
                </div>
                <div class="topEchartsRight topSmallBox">
                    <div class="topLeft">
                        <span class="title">总用户量</span>
                        <span class="number">{{ topRData.total || 0 }}</span>
                        <span class="comparison">较昨天&emsp;
                            <span class="comparisonGreen" v-if="topLData.increase >= 0">{{ topLData.increase
                            }}</span>
                            <span class="comparisonRed" v-else>{{ topLData.increase
                            }}</span>
                        </span>
                    </div>
                    <div class="topRight">
                        <div class="chartBox" ref="topR"></div>
                    </div>
                </div>
            </div>
            <div class="bottomEchartsBox">
                <div class="headerBox">
                    <h4>用户增长趋势</h4>
                    <div class="dateMonth">
                        <el-date-picker v-model="monthData" type="month" placeholder="选择月份" format="YYYY-MM"
                            @change="getUserChart" />
                    </div>
                </div>
                <div class="footerBox">
                    <div class="footerChart" ref="footerI"></div>
                </div>
            </div>
        </div>
        <!-- <div class="timeBox"> -->
        <!-- <div class="outLogin">
                <el-button type="primary" class="loginOut" v-loading="loading" @click="outLogin">退出登录</el-button>
            </div> -->
        <!-- <div class="clockBox">
                <canvas ref="canvas" height="200" width="200"></canvas>
            </div>
            <div class="timeItem">
                <div class="time">{{ time.time }}</div>
                <div class="second">{{ time.second }}</div>
            </div>
            <div class="dateItem">
                <div class="week">{{ time.week }}</div>
                <div class="date">{{ time.date }}</div>
            </div> -->
        <!-- </div> -->
        <!-- <div class="userInformation">
            <div class="account borderL">
                <img src="@/assets/icon/user.svg" alt="">
                <span>姓名</span>
            </div>
            <div class="Name">
                <span>{{ userName }}</span>
            </div>
            <div class="account">
                <img src="@/assets/icon/role.svg" alt="">
                <span>角色</span>
            </div>
            <div class="Name borderR">
                <span>{{ role_id }}</span>
            </div>
        </div> -->
        <div class="footer" v-if="famousSentence">
            <p>“{{ famousSentence.hitokoto }}”</p>
            <p>
                《{{ famousSentence.from }}》
            </p>
            <p>——————{{ famousSentence.from_who ? famousSentence.from_who : '佚名' }}——————</p>
        </div>
    </div>
</template>
<script setup lang='ts' name="Home">
import { ref, onMounted, onBeforeUnmount } from 'vue';
import { useRouter } from 'vue-router'; // 确保已经安装并正确配置了 vue-router
import { logout } from '@/api/login.ts'
import { content, comment, short, user } from '@/api/home/home.ts'
import { useRouteStore } from '@/stores/modules/counter.ts'
import * as echarts from 'echarts';
const routeStore = useRouteStore();
import dayjs from 'dayjs';
const router = useRouter(); // 获取路由实例
const timer: any = ref(null);
const time: any = ref({});
const loading = ref(false)
// const userName = localStorage.getItem("userName");
// const role_id = localStorage.getItem("role_id");
const getDate = () => {
    time.value = parseTime(new Date());
    // console.log(21, time.value);
};
// 退出登录提示词语
const logOutPrompt = [
    'see you，期待下次相遇',
    '虽然追求的目标截然不同，但群星的轨道终将彼此交汇',
    '起风了',
    '转身离开，你有话说不出来',
    '没有人会一直等你，除了我',
    '命运十字路口，谢谢你曾挽留',
    '希望终点是爱琴海',
    '我在最初的地方等你凯旋',
    '阔别重逢日，应是雪满山',
]
const getRandomPrompt = () => {
    return logOutPrompt[Math.floor(Math.random() * logOutPrompt.length)];
}
const outLogin = (() => {
    ElMessageBox.confirm(
        '确定退出登录?',
        '退出',
        {
            confirmButtonText: '确 定',
            cancelButtonText: '取 消',
            type: 'warning',
        }
    )
        .then(() => {
            logout({}).then((res: any) => {
                loading.value = true
                if (res.code === 200) {
                    // ElMessage({
                    //     // message: '删除成功',
                    //     type: 'success',
                    // })
                    ElMessage({
                        type: 'success',
                        message: getRandomPrompt(),
                    })
                    localStorage.removeItem("token");
                    localStorage.removeItem("userName");
                    localStorage.removeItem("role_id");
                    loading.value = false
                    router.push('/login');
                }
            }).catch(() => {
                ElMessage({
                    message: '请求错误，无法退出登录，需要联系管理员处理',
                    type: 'error',
                })
            }).finally(() => {

            })
        })
        .catch(() => {
            // ElMessage({
            //     type: 'info',
            //     message: '取消操作',
            // })
        })
})
// 根据传入的时间，处理成需要的对象函数
const parseTime = (time: any) => {
    draw(time);
    let resObj: any = {};
    let week = ['日', '一', '二', '三', '四', '五', '六'];
    resObj.date = dayjs(time).format('YYYY年MM月DD日');
    resObj.week = `星期${week[dayjs(time).day()]}`;
    resObj.time = dayjs(time).format('HH:mm');
    resObj.second = dayjs(time).format('ss');
    return resObj;
};
const canvas = ref();
//描绘时分秒小数和小数点
// 绘制表盘
const radius = 80;
const cWidth = 200;
const drawBackground = () => {
    ctx.value.save();
    // ctx.value.translate(radius, radius); //中心原点位置
    const width = cWidth;
    const height = cWidth;
    const R = width / 2; //圆半径
    const r = (R / 3) * 2;
    //设置坐标轴原点
    ctx.value.translate(width / 2, height / 2);
    // 圆心
    ctx.value.beginPath();
    // ctx.value.arc(0, 0, 10, 0, 2 * Math.PI, true);
    ctx.value.fill();
    ctx.value.closePath();
    // 表盘刻度（大格）
    ctx.value.beginPath();
    ctx.value.lineWidth = 2;
    for (var i = 0; i < 12; i++) {
        ctx.value.beginPath();
        ctx.value.strokeStyle = 'rgba(189, 195, 199, 1)';
        ctx.value.rotate(Math.PI / 6);
        ctx.value.moveTo(R, 0);
        ctx.value.lineTo(r, 0);
        ctx.value.stroke();
    }
    ctx.value.closePath();
    // 表盘刻度（小格）
    ctx.value.beginPath();
    ctx.value.lineWidth = 1;
    for (var i = 0; i < 60; i++) {
        ctx.value.beginPath();
        ctx.value.strokeStyle = 'rgba(189, 195, 199, 0.7)';
        ctx.value.rotate(Math.PI / 30);
        ctx.value.moveTo(R, 0);
        ctx.value.lineTo(R - 10, 0);
        ctx.value.stroke();
    }
    ctx.value.closePath();
};

//描绘时针
const drawHour = (hour: number, minute: number) => {
    ctx.value.save();
    ctx.value.beginPath();
    ctx.value.strokeStyle = '#000';
    let rad = ((2 * Math.PI) / 12) * hour;
    let mrad = ((2 * Math.PI) / 12 / 60) * minute;
    ctx.value.rotate(rad + mrad);
    ctx.value.lineWidth = 4;
    ctx.value.lineCap = 'round';
    ctx.value.moveTo(0, 10);
    ctx.value.lineTo(0, -radius + 30);
    ctx.value.stroke();
    ctx.value.restore();
};
//描绘分针
const drawMinute = (minute: number) => {
    ctx.value.save();
    ctx.value.beginPath();
    let rad = ((2 * Math.PI) / 60) * minute;
    ctx.value.rotate(rad);
    ctx.value.strokeStyle = '#000';
    ctx.value.lineWidth = 3;
    ctx.value.lineCap = 'round';
    ctx.value.moveTo(0, 10);
    ctx.value.lineTo(0, -radius + 10);
    ctx.value.stroke();
    ctx.value.restore();
};
//描绘秒针
const drawSecond = (second: number) => {
    ctx.value.save();
    ctx.value.beginPath();
    ctx.value.fillStyle = '#C14543';
    ctx.value.lineWidth = 2;
    ctx.value.lineCap = 'round';
    let rad = ((2 * Math.PI) / 60) * second;
    ctx.value.rotate(rad);
    ctx.value.moveTo(-2, 20);
    ctx.value.lineTo(2, 20);
    ctx.value.lineTo(1, -radius + 5);
    ctx.value.lineTo(-1, -radius + 5);
    ctx.value.fill();
    ctx.value.restore();
};
//中间固定圆点
const drawDot = () => {
    ctx.value.beginPath();
    ctx.value.fillStyle = '#C14543';
    ctx.value.arc(0, 0, 4, 0, 2 * Math.PI, false);
    ctx.value.fill();
};
const draw = (now: any) => {
    ctx.value.clearRect(0, 0, cWidth, cWidth);
    let hour = now.getHours();
    let minute = now.getMinutes();
    let second = now.getSeconds();
    drawBackground();
    drawHour(hour, minute);
    drawMinute(minute);
    drawSecond(second);
    drawDot();
    ctx.value.restore();
};
// 获取名言名句
const famousSentence = ref('')
const getText = async () => {
    const response = await fetch('https://v1.hitokoto.cn/?c=d&c=e&c=h&c=i&c=k');
    if (response.ok) {
        const data = await response.json();
        famousSentence.value = data
    }
}
const ctx = ref();
const topL = ref(null)
const topLData = ref({})
const topI = ref(null)
const topIData = ref({})
const topR = ref(null)
const topRData = ref({})
const footerI = ref(null)
const footerIData = ref({})
const monthData = ref('')
const setTopL = (content: object) => {
    if (topL.value) {
        let chartInstance = echarts.init(topL.value)
        // 配置项
        const option = {
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                }
            },
            grid: {
                top: '6%',
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            xAxis: [
                {
                    type: 'category',
                    data: [],
                    axisTick: {
                        show: false,
                        alignWithLabel: true
                    },
                    axisLine: {
                        show: false,
                    },
                    splitLine: {
                        show: false,
                    },
                    scale: true,
                    splitNumber: 1,
                    axisLabel: {
                        show: false
                    }
                }
            ],
            yAxis: [
                {
                    data: [],
                    type: 'category',
                    axisTick: {
                        show: false,
                    },
                    axisLine: {
                        show: false,
                    },
                    splitLine: {
                        show: false,
                    },
                }
            ],
            series: [
                {
                    name: 'Direct',
                    type: 'bar',
                    barWidth: '60%',
                    data: content.content_value,
                    itemStyle: {
                        borderRadius: [6, 6, 6, 6],
                        color: '#2CAB40'
                    },
                }
            ]
        };

        // 使用配置项渲染图表
        chartInstance.setOption(option)
    }
}
const setTopI = (content: object) => { // 上中图
    let chartInstance = echarts.init(topI.value)
    lineChart(chartInstance, content)
}
const setTopR = (content: object) => { // 上右图
    let chartInstance = echarts.init(topR.value)
    lineChart(chartInstance, content)
}
const lineChart = (chartInstance: any, content: object) => {// 折线图
    const option = {
        grid: {
            top: '6%',
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            data: [],
            axisTick: {
                show: false,
                alignWithLabel: true
            },
            axisLine: {
                show: false,
            },
            splitLine: {
                show: false,
            },
            scale: true,
            splitNumber: 1,
            axisLabel: {
                show: false
            }
        },
        yAxis: {
            data: [],
            type: 'category',
            axisTick: {
                show: false,
            },
            axisLine: {
                show: false,
            },
            splitLine: {
                show: false,
            },
        },
        series: [
            {
                data: [820, 932, 901, 934, 1290, 1330, 1320],
                type: 'line',
                smooth: true,
                showSymbol: false,
                itemStyle: {
                    color: '#165DFF'
                },
            }
        ]
    }
    chartInstance.setOption(option)
}
const setFooterChart = (content: object) => {// 下方图
    let chartInstance = echarts.init(footerI.value)
    let option = {
        grid: {
            top: '6%',
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            data: content.add_time
        },
        yAxis: {
            type: 'value'
        },
        series: [
            {
                data: content.user_value,
                type: 'line',
                itemStyle: {
                    color: '#2478F2'
                },
            }
        ]
    };
    chartInstance.setOption(option)
}
const getChartData = () => { // 获取图表数据
    content().then((res: object) => {
        if (res.code === 200) {
            topLData.value = res.data
            setTopL(topLData.value)
        } else {
            ElMessage.error(`错误!${res.msg}`)
        }
    })
    comment().then((res: object) => {
        if (res.code === 200) {
            topIData.value = res.data
            setTopI(topIData.value)
        } else {
            ElMessage.error(`错误!${res.msg}`)
        }
    })
    short().then((res: object) => {
        if (res.code === 200) {
            topRData.value = res.data
            setTopR(topRData.value)
        } else {
            ElMessage.error(`错误!${res.msg}`)
        }
    })
}
const getUserChart = () => {
    let para = {
        time: dayjs(monthData.value).format('YYYY.MM')
    }
    user(para).then((res: object) => {
        if (res.code === 200) {
            topRData.value = res.data
            topRData.value.add_time = topRData.value.add_time.map(dateStr => {
                const parts = dateStr.split('.');
                return parts.length >= 3 ? parts[2] : dateStr;
            })
            setFooterChart(topRData.value)
        } else {
            ElMessage.error(`错误!${res.msg}`)
        }
    })
}

const getMonth = () => {// 获取当前月份
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从 0 开始
    monthData.value = `${year}-${month}`;
}
onMounted(() => {
    getMonth()
    // ctx.value = canvas.value.getContext('2d');
    // timer.value = setInterval(() => {
    //     getDate();
    // }, 1000);
    // routeStore.setRouteName('0');
    window.addEventListener('beforeunload', routeStore.reset());
    getText()
    getChartData()// 获取并挂载图表
    getUserChart()// 获取并挂载图表
});
onBeforeUnmount(() => {
    window.removeEventListener('beforeunload', routeStore.reset())
    clearInterval(timer.value);
    timer.value = null;
});
</script>
<style lang='scss' scoped>
.BoxBg {
    width: 100%;
    height: 100%;
    // background: linear-gradient(180deg, #F6F6F6, #F0D3D3);
    position: relative;

    .bodyBox {
        width: 70%;
        height: calc(100% - 30px);
        margin: 0 auto;
        padding-top: 20px;

        .topEchartsBox {
            width: 100%;
            height: 23%;
            display: flex;
            justify-content: space-between;

            .topSmallBox {
                width: 33%;
                height: 100%;
                display: flex;
                justify-content: center;

                .topLeft {
                    width: 35%;
                    height: 100%;

                    span {
                        display: block;
                        margin-left: 20px;
                    }

                    .title {
                        margin-top: 10%;
                    }

                    .number {
                        font-size: 24px;
                        margin-top: 36%;
                    }

                    .comparison {
                        font-size: 12px;
                        margin-top: 7%;

                        .comparisonGreen {
                            display: inline;
                            margin-left: 0;
                            color: #00B42A;
                        }

                        .comparisonRed {
                            display: inline;
                            margin-left: 0;
                            color: #F44C4C;
                        }
                    }
                }

                .topRight {
                    width: 65%;
                    height: 100%;
                    display: inline-block;

                    .chartBox {
                        width: 95%;
                        height: 60%;
                        margin-top: 18%;
                    }
                }

            }

            .topEchartsLeft {
                background: linear-gradient(135deg, #F5FEF2, #E6FEEE);
            }

            .topEchartsInt {
                background: linear-gradient(135deg, #F2F9FE, #E5F3FE);
            }

            .topEchartsRight {
                background: linear-gradient(135deg, #F5F5FF, #ECECFF);
            }
        }

        .bottomEchartsBox {
            width: 80%;
            height: 60%;
            margin: 0 auto;
            margin-top: 4%;

            .headerBox {
                width: 100%;
                height: 15%;
                display: flex;
                justify-content: space-between;

                h4 {
                    display: inline-block;
                    margin-top: 20px;
                    margin-left: 20px;
                }

                .dateMonth {
                    display: inline-block;
                    margin-top: 20px;
                    margin-right: 20px;
                }
            }

            .footerBox {
                width: 100%;
                height: 85%;

                .footerChart {
                    width: 100%;
                    height: 100%;
                }
            }
        }
    }

    // .timeBox {
    //     width: 100%;
    //     margin: 0 auto;
    //     // background: linear-gradient(to right bottom, #7cafe3, #046ac1);
    //     display: flex;
    //     // justify-content: center;
    //     // cursor: default;
    //     // user-select: none;

    //     .outLogin {
    //         width: 100%;
    //         text-align: right;

    //         :deep(.el-button) {
    //             width: 80px;
    //             height: 36px;
    //             background-color: #DE868F;
    //             border: 1px solid #BBBBBB;
    //             margin: 10px 0 0 0;
    //             padding: 0;
    //             border-radius: 8px;
    //             margin-right: 20px;
    //         }
    //     }

    //     .clockBox {
    //         width: 240px;
    //         padding-top: 120px;
    //     }

    //     .timeItem {
    //         display: flex;
    //         width: 220px;
    //         color: black;
    //         padding-top: 165px;

    //         .time {
    //             font: 60px/100px 'pf';
    //         }

    //         .second {
    //             font: 30px/30px 'pf';
    //             margin: 45px 0 0 20px;
    //         }
    //     }

    //     .dateItem {
    //         width: 200px;
    //         color: black;
    //         padding-top: 190px;
    //         padding-left: 40px;

    //         .week {
    //             font: 22px/22px 'pf';
    //         }

    //         .date {
    //             margin-top: 10px;
    //             font: 18px/18px 'pf';
    //         }
    //     }
    // }

    // .userInformation {
    //     width: 600px;
    //     margin: 0 auto;
    //     margin-top: 300px;
    //     display: flex;
    //     justify-content: center;

    //     .account {
    //         width: 120px;
    //         height: 50px;
    //         background: #BEBEBE;
    //         display: flex;
    //         align-items: center;

    //         img {
    //             width: 30px;
    //             height: 30px;
    //             margin-right: 5px;
    //             margin-left: 5px;
    //         }

    //         span {
    //             font-size: 16px;
    //             font-weight: bold;
    //             color: black;
    //         }
    //     }

    //     .Name {
    //         width: 180px;
    //         height: 50px;
    //         background: #fff;
    //         display: flex;
    //         align-items: center;

    //         span {
    //             margin-left: 5px;
    //             overflow: hidden;
    //             text-overflow: ellipsis;
    //             white-space: nowrap;
    //             color: black;
    //         }
    //     }
    // }

    .footer {
        width: 100%;
        min-height: 30px;
        // display: flex;
        // justify-content: center;
        // align-items: center;
        text-align: center;
        position: absolute;
        bottom: 0;
        color: #7f8c8d;

        p {
            margin: 0;
            padding: 0;
        }
    }

    .borderL {
        border-radius: 10px 0 0 10px;
    }

    .borderR {
        border-radius: 0 10px 10px 0;
    }
}
</style>